package com.loc.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loc.dao.MenusDao;
import com.loc.pojo.Menu;

@Controller
@RequestMapping(value = "/menu")
public class MenuService extends BaseService {

	@Autowired
	private MenusDao menuDao;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getMenuTree.json", method = RequestMethod.POST)
	public @ResponseBody Map getMenu(HttpServletRequest request, HttpSession session) {
		UserDetails userDetails = null;
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
			userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		} else {
			map.put("failture", true);
			map.put("msg", "没有权限!");
			return map;
		}
		try {
			list = menuDao.findMenuByUser(userDetails);
			List returnList = tree(list, 0, 0);
			map.put("success", true);
			map.put("msg", returnList);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failture", true);
			map.put("msg", "系统出错!请尝试刷新页面!");
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getAllMenuTree.json", method = RequestMethod.POST)
	public @ResponseBody Map getAllMenu(HttpServletRequest request, HttpSession session) {
		UserDetails userDetails = null;
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
				userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			} else {
				map.put("failture", true);
				map.put("msg", "没有权限!");
				return map;
			}
			list = menuDao.findAllMenu(userDetails);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failture", true);
			map.put("msg", "系统出错!请尝试刷新页面!");
		}
		map.put("seccess", true);
		map.put("msg", tree(list, 0, 1));
		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getMenuByMenuId.json", method = RequestMethod.POST)
	public @ResponseBody Map getMenuByMenuId(HttpServletRequest request, HttpSession session) {
		String menu_id = request.getParameter("menu_id");
		String rp = request.getParameter("rp");
		String page = request.getParameter("page");
		int startRow = 0;
		int rowsCount = 20;
		if (menu_id == null || "".equals(menu_id)) {
			menu_id = "0";
		}
		if (rp != null && !"".equals(rp)) {
			rowsCount = Integer.valueOf(rp);
		}
		if (page != null && !"".equals(page)) {
			startRow = (Integer.valueOf(page) - 1) * rowsCount;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		UserDetails userDetails = null;
		List<Map<String, Object>> list = null;
		try {
			if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
				userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			} else {
				map.put("failture", true);
				map.put("msg", "没有权限!");
				return map;
			}
			list = menuDao.findMenuByMenuId(userDetails);
			List<Map<String, Object>> returnList = new ArrayList<Map<String, Object>>();
			getMenuByMenuId(list, Integer.valueOf(menu_id), returnList, 1);
			int total = returnList.size();
			map.put("total", total);
			map.put("page", page);
			map.put("rows", returnList.subList(startRow,(startRow + rowsCount) < total ? startRow + rowsCount : total));
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failture", true);
			map.put("msg", "系统出错!请尝试刷新页面!");
		}
		return map;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/findMenus.json", method = RequestMethod.POST)
	public @ResponseBody Map findMenus(HttpServletRequest request, HttpSession session) {
		String rp = request.getParameter("rp");
		String page = request.getParameter("page");
		int startRow = 0;
		int rowsCount = 15;
		if (rp != null && !"".equals(rp)) {
			rowsCount = Integer.valueOf(rp);
		}
		if (page != null && !"".equals(page)) {
			startRow = (Integer.valueOf(page) - 1) * rowsCount;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		UserDetails userDetails = null;
		List<Map<String, Object>> list = null;
		try {
			if (SecurityContextHolder.getContext().getAuthentication().isAuthenticated()) {
				userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			} else {
				map.put("failture", true);
				map.put("msg", "没有权限!");
				return map;
			}
			String menu_name = request.getParameter("menu_name");
			String menu_type = request.getParameter("menu_type");
			String isleaf = request.getParameter("isleaf");
			String isrel = request.getParameter("menu_rel");
			String isvisiable = request.getParameter("isvisiable");
			String menu_parent = request.getParameter("menu_parent");
			Map<String,Object> m = new HashMap<String,Object>();
			if(menu_name!=null&&!"".equals(menu_name)){
				m.put("menu_name", menu_name);
			}
			if(menu_type!=null&&!"".equals(menu_type)){
				m.put("menu_type", menu_type);
			}
			if(isleaf!=null&&!"".equals(isleaf)){
				m.put("isleaf", isleaf);
			}
			if(isrel!=null&&!"".equals(isrel)){
				m.put("menu_rel", isrel);
			}
			if(isvisiable!=null&&!"".equals(isvisiable)){
				m.put("isvisiable", isvisiable);
			}
			if(menu_parent!=null&&!"".equals(menu_parent)){
				m.put("menu_parent", menu_parent);
			}
			list = menuDao.findMenus(m,userDetails,startRow,rowsCount);
			int total = list.size();
			for(int i=0;i<total;i++){
				Map mm = list.get(i);
				mm.put("ids", startRow+i+1);
			}
			map.put("total", total);
			map.put("page", page);
			map.put("rows", list);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failture", true);
			map.put("msg", "系统出错!请尝试刷新页面!");
		}
		return map;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addMenu.json", method = RequestMethod.POST)
	public @ResponseBody Map addMenu(HttpServletRequest request, HttpSession session) {
		String menu_name = request.getParameter("menu_name");
		String menu_url = request.getParameter("menu_url");
		String menu_parent = request.getParameter("menu_parent");
		String menu_icon = request.getParameter("menu_icon");
		String isleaf = request.getParameter("isleaf");
		String isvisiable = request.getParameter("isvisiable");
		String issys = request.getParameter("issys");
		String menu_rel = request.getParameter("isrel");
		String menu_type = request.getParameter("menu_type");
		String memo = request.getParameter("memo");
		Menu menu = new Menu();
		boolean flag = false;
		Map<String, Object> map = new HashMap<String, Object>();
		if (menu_name == null || "".equals(menu_name)) {
			flag = true;
			map.put("msg", "菜单名称不能空");
		}
		if (menu_url == null || "".equals(menu_url)) {
			flag = true;
			map.put("msg", "URL不能为空");
		}
		int parent = 0;
		if (menu_parent == null || menu_parent.equals("")) {
			flag = true;
			map.put("msg", "父节点不能为空");
		} else {
			parent = Integer.valueOf(menu_parent);
		}
		if (flag) {
			map.put("failture", true);
		} else {
			menu.setMenu_name(menu_name);
			menu.setMenu_url(menu_url);
			menu.setMenu_parent(parent);
			menu.setMenu_icon(menu_icon==null?"":menu_icon);
			menu.setIsleaf(Integer.valueOf(isleaf));
			menu.setIsvisiable(Integer.valueOf(isvisiable));
			menu.setIssys(Integer.valueOf(issys));
			menu.setMenu_rel(Integer.valueOf(menu_rel));
			menu.setMenu_type(Integer.valueOf(menu_type));
			menu.setMemo(memo);
			try {
				menuDao.addMenu(menu);
				map.put("success", true);
				map.put("msg", "添加成功!");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("failtrue", true);
				map.put("msg", "添加失败!请尝试刷新页面!");
			}
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/selectMenu.json", method = RequestMethod.POST)
	public @ResponseBody Map selectMenu(HttpServletRequest request, HttpSession session) {
		String menu_id = request.getParameter("menu_id");
		Map<String, Object> map = new HashMap<String, Object>();
		if (menu_id == null || "".equals("menu_id")) {
			map.put("failtrue", true);
			map.put("msg", "获取失败!请尝试刷新页面!");
		}
		try {
			map = menuDao.selectMenu(menu_id);
			if (map.get("issys").toString().equals("1")) {
				map = new HashMap<String, Object>();
				map.put("failtrue", true);
				map.put("msg", "系统默认不能修改!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failtrue", true);
			map.put("msg", "获取失败!请尝试刷新页面!");
		}
		return map;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/updateMenu.json", method = RequestMethod.POST)
	public @ResponseBody Map updateMenu(HttpServletRequest request, HttpSession session) {
		String menu_id = request.getParameter("menu_id");
		String menu_name = request.getParameter("menu_name");
		String menu_url = request.getParameter("menu_url");
		String menu_parent = request.getParameter("menu_parent");
		String menu_icon = request.getParameter("menu_icon");
		String isleaf = request.getParameter("isleaf");
		String isvisiable = request.getParameter("isvisiable");
		String issys = request.getParameter("issys");
		String menu_rel = request.getParameter("isrel");
		String menu_type = request.getParameter("menu_type");
		String memo = request.getParameter("memo");
		Menu menu = new Menu();
		boolean flag = false;
		Map<String, Object> map = new HashMap<String, Object>();
		if (menu_name == null || "".equals(menu_name)) {
			flag = true;
			map.put("msg", "菜单名称不能空");
		}
		if (menu_url == null || "".equals(menu_url)) {
			flag = true;
			map.put("msg", "URL不能为空");
		}
		int parent = 0;
		if (menu_parent == null || menu_parent.equals("")) {
			flag = true;
			map.put("msg", "父节点不能为空");
		} else {
			parent = Integer.valueOf(menu_parent);
		}
		if (flag) {
			map.put("failture", true);
		} else {
			menu.setMenu_id(Integer.valueOf(menu_id));
			menu.setMenu_name(menu_name);
			menu.setMenu_url(menu_url);
			menu.setMenu_parent(parent);
			menu.setMenu_icon(menu_icon);
			menu.setIsleaf(Integer.valueOf(isleaf));
			menu.setIsvisiable(Integer.valueOf(isvisiable));
			menu.setIssys(Integer.valueOf(issys));
			menu.setMenu_rel(Integer.valueOf(menu_rel));
			menu.setMenu_type(Integer.valueOf(menu_type));
			menu.setMemo(memo);
			try {
				menuDao.updateMenu(menu);
				map.put("success", true);
				map.put("msg", "修改成功!");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("failtrue", true);
				map.put("msg", "修改失败!请尝试刷新页面!");
			}
		}
		return map;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/deleteMenu.json", method = RequestMethod.POST)
	public @ResponseBody Map deleteMenu(HttpServletRequest request, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String menu_ids = request.getParameter("menu_ids");
			if(menu_ids==null||menu_ids.equals("")){
				map.put("failtrue", true);
				map.put("msg","删除失败!请尝试刷新页面!");
			}else{
				menu_ids = new StringBuffer(menu_ids.trim()).deleteCharAt(menu_ids.length()-1).toString();
			}
			List<Menu> list = menuDao.getMenuByIds(menu_ids);
			for(Menu menu:list){
				if(menu.getIssys()!=0){
					map.put("failtrue", true);
					map.put("msg","<font color='red'>["+menu.getMenu_name()+"]</font>-----系统默认不能删除!");
					return map;
				}else{
					menuDao.deleteMenu(menu.getMenu_id()+"");
				}
			}
			map.put("success", true);
			map.put("msg","删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("failtrue", true);
			map.put("msg","删除失败!请尝试刷新页面!");
		}
		return map;
	}
	private List<Map<String, Object>> tree(List<Map<String, Object>> list,int menu_id, int type) {
		List<Map<String, Object>> tempList = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> map : list) {
			Map<String, Object> m = null;
			if (Integer.valueOf(map.get("menu_parent").toString()) == menu_id) {
				m = new HashMap<String, Object>();
				m.put("name", map.get("menu_name"));
				m.put("menu_type", map.get("menu_type"));
				m.put("menu_id", map.get("menu_id"));
				if (type == 1) {
					m.put("isParent",map.get("menu_type").toString().equals("0")|| map.get("menu_type").toString().equals("2") ? true : false);
					if (map.get("menu_type").toString().equals("0")|| map.get("menu_type").toString().equals("2")) {
						List<Map<String, Object>> l = tree(list, Integer.valueOf(map.get("menu_id").toString()), type);
						if (l != null) {
							m.put("childs", l);
						}
					}
				} else {
					m.put("isParent",map.get("isleaf").toString().equals("0") ? true: false);
					if (map.get("isleaf").toString().equals("0")) {
						List<Map<String, Object>> l = tree(list, Integer.valueOf(map.get("menu_id").toString()), type);
						if (l != null) {
							m.put("childs", l);
						}
					}
				}
				m.put("menu_url", map.get("menu_url"));
				if (map.get("menu_icon") != null) {
					m.put("icon", map.get("menu_icon"));
				}
				tempList.add(m);
			}
		}
		if (tempList.size() == 0) {
			tempList = null;
		}
		return tempList;
	}

	private int getMenuByMenuId(List<Map<String, Object>> doList, int menu_id,List<Map<String, Object>> returnList, int count) throws Exception{
		for (Map<String, Object> map : doList) {
			if (Integer.valueOf(map.get("menu_id").toString()) == menu_id) {
				if (map.get("menu_icon") == null) {
					map.put("menu_icon", "");
				}
				map.put("id", map.get("menu_id"));
				map.put("ids", count);
				returnList.add(map);
				count++;
			}
			if (Integer.valueOf(map.get("menu_parent").toString()) == menu_id) {
				if (map.get("isleaf").toString().equals("0")|| map.get("menu_type").toString().equals("0")) {
					count = getMenuByMenuId(doList, Integer.valueOf(map.get("menu_id").toString()), returnList, count);
				} else {
					if (map.get("menu_icon") == null) {
						map.put("menu_icon", "");
					}
					map.put("id", map.get("menu_id"));
					map.put("ids", count);
					returnList.add(map);
					count++;
				}
			}
		}
		return count;
	}
}
